const mixin = require("../../mixins");
Component({
  behaviors: [mixin],
  data: {
    isBasicsTag: false,
    basicsTag: null,
    timers: [],

    activityStatus: 1, // 0未开始 1登记 2公布 3结束
    drawButtonText: "",
    drawTitleText: "",
    drawButtonColor: "#000",
    drawTitleColor: "#000",
    showDate: "",
    timer: null,
    cardItem: null,
    remindMeStatus: "", //设置订阅提醒
  },

  properties: {
    itemObj: Object,
    cardComp: Object,
    mf_data: Object
  },
  attached() {
    this.balloutInit();
  },
  clickTimer: null,
  methods: {
    async balloutInit() {
      const page = getCurrentPages();
      let {
        basicsTag,
        isBasicsTag = false,
        navName,
        userOrderLists = []
      } = page[page.length - 1].data;
      let {
        itemObj,
      } = this.properties;
      let dealObj = JSON.parse(JSON.stringify(itemObj));
      let setTopBarStatus = false;
      let customerInfo = wx.getStorageSync('customerInfo') || getApp().globalData.customerInfo;
      let merchantInfo = wx.getStorageSync('merchantInfo') || getApp().globalData.merchantInfo;
      let memberLevelId = 0;
      const memberLevelData = wx.getStorageSync('memberDetails');
      if (memberLevelData && memberLevelData.memberLevelId) memberLevelId = memberLevelData.memberLevelId;

      if (dealObj && dealObj.goods) {
        const goods = dealObj.goods;
        const _drawInfo = await this.getDrawInfo(customerInfo, merchantInfo, goods.itemId, goods.valueId,
          memberLevelId)
        dealObj.drawInfo = _drawInfo;
        if (dealObj.drawInfo && dealObj.drawInfo.activitySwitch) {
          //  将抽签购商品 传递至父级页面
          if (page[page.length - 1].$vm.setTopBar) page[page.length - 1].$vm.setTopBar(dealObj);
          setTopBarStatus = true;
          this.statusChange(dealObj.drawInfo, goods.itemName, userOrderLists, goods.itemId);
        }
      }

      this.setData({
        cardItem: dealObj,
        dchildren: dealObj,
        basicsTag: basicsTag || [],
        isBasicsTag: isBasicsTag || ""
      }, () => {
        //  若暂无抽签购活动，则需要手动触发横幅方法
        if (!setTopBarStatus && page[page.length - 1].$vm.setTopBar) page[page.length - 1].$vm.setTopBar(
        null);
      });
    },
    /**
     * 判断当前商品是否参与抽签购
     * @param {Object} customerInfo
     * @param {Object} merchantInfo
     * @param {Object} goodsId  商品itemId
     * @param {Object} valueId  商品valueId
     * @param {Object} memberLevelId  会员ID
     * @param {Object} orderLists 用户订单列表
     */
    async getDrawInfo(customerInfo, merchantInfo, itemId, valueId, memberLevelId, orderLists) {
      const api = getApp().globalData.api;
      if (api && api.getDrawInfo) {
        let json = await api.getDrawInfo({
          method: "GET",
          query: {
            store_id: merchantInfo.cloudMerchantStoreId,
            merchant_id: merchantInfo.cloudMerchantId,
            customer_id: customerInfo ? customerInfo.customerId : "",
            item_id: itemId,
            value_id: valueId,
          },
        });
        let backData = {};
        if (json && json.code === 1000 && json.data) {
          backData.order = null;
          const _data = json.data;
          //  本次活动仅限受邀用户参与
          let verifyDrawRes = await api.verifyDrawIdentify({
            method: 'POST',
            header: {
              jwt: customerInfo ? customerInfo.jwt : ''
            },
          }, _data.activitySelectionId);

          if (verifyDrawRes.code !== 1000) {
            backData.activitySwitch = false;
            return backData;
          }
          backData.activitySwitch = true;

          backData.ruleId = _data.activitySelectionDesc || 'drawRule';
          backData.activityInfo = _data;

          let createTime = _data.createTime;
          let drawStartTime = _data.activitySelectionStartTime;
          let drawEndTime = _data.activitySelectionEndTime;
          let promulgateTime = _data.promulgateTime;
          let activityEndTime = _data.buyEndTime;
          let activityStopTime = _data.activityStopTime;
          backData.drawEndTime = this.formatDate(drawEndTime)
          let exCreateTime, exStartTime, exEndTime, expromulgateTime, buyEndTime;
          exCreateTime = createTime && this.formatTimeStamp(createTime);
          exStartTime = drawStartTime && this.formatTimeStamp(drawStartTime);
          expromulgateTime = promulgateTime && this.formatTimeStamp(promulgateTime);
          exEndTime = drawEndTime && this.formatTimeStamp(drawEndTime);
          buyEndTime = activityEndTime && this.formatTimeStamp(activityEndTime);
          activityStopTime = activityStopTime && this.formatTimeStamp(activityStopTime);
          backData.exTime = {
            exCreateTime,
            exStartTime,
            expromulgateTime,
            exEndTime,
            buyEndTime,
            activityStopTime
          }
          backData.drawStartTrackTime = this.trackDate(exStartTime)
          backData.promulgateTrackTime = this.trackDate(expromulgateTime)
          backData.activityEndTrackTime = this.trackDate(buyEndTime)
          backData.exEndTrackTime = this.trackDate(exEndTime)
          backData.buyEndTrackTime = this.trackDate(buyEndTime)
          backData.memberLevelId = memberLevelId;
          backData.apiEnvironment = api.environment;
        } else {
          backData.activitySwitch = false;
        }
        return backData;
      }
      return null;
    },
    /**
     * 查询抽签购商品是否已订阅消息
     * @param {Object} itemName   商品名称
     * @param {Object} activityInfo  抽签购活动信息，接口api.getDrawInfo返回的内容
     */
    async isSecondRemindRquest(itemName, activityInfo, customerInfo) {
      try {
        const api = getApp().globalData.api;
        let userSpecialInfo = wx.getStorageSync('userSpecialInfo');
        const accountInfo = wx.getAccountInfoSync();
        if (!userSpecialInfo || !accountInfo) return false;
        let res = await api.getSaleMessage({
          method: 'POST',
          header: {
            jwt: customerInfo ? customerInfo.jwt : ''
          },
          query: {
            name: '甄选佳酿活动开始提醒',
            appId: accountInfo.miniProgram.appId,
            openId: userSpecialInfo.openid,
            params: {
              itemName: itemName,
              startTime: activityInfo.activitySelectionStartTime,
              activityId: activityInfo.activitySelectionId
            }
          }
        });
        if (res.code !== 1000) {
          return false
        } else {
          return true
        }
      } catch (e) {
        return false;
      }
    },
    //埋点北京时间转换成utc时间
    trackDate(timeStamp) {
      let timeDifference = timeStamp - 8 * 60 * 60 * 1000;
      let utcDateTime = this.timeFormat(timeDifference, true)
      return utcDateTime
    },
    // 转时间戳
    formatTimeStamp(date) {
      let systemInfo = wx.getStorageSync('systemInfo');
      let isIos = systemInfo.system.indexOf("iOS");
      if (isIos == 0) {
        date = date && new Date(date.replace(/-/g, "/")).getTime();
      } else {
        date = date && new Date(date).getTime();
      }
      return date;
    },
    // 13位时间戳转日期
    timeFormat(time, flag) {
      var date = new Date(time); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y, M;
      if (flag) {
        Y = date.getFullYear() + "-";
        M =
          (date.getMonth() + 1 < 10 ?
            "0" + (date.getMonth() + 1) :
            date.getMonth() + 1) + "-";
      } else {
        Y = date.getFullYear() + "/";
        M =
          (date.getMonth() + 1 < 10 ?
            "0" + (date.getMonth() + 1) :
            date.getMonth() + 1) + "/";
      }
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

      let strDate = Y + M + D + h + m + s;
      return strDate;
    },
    //  抽签购商品按钮状态判断
    async statusChange(obj, itemName, orderLists, itemId) {
      try {
        let customerInfo = wx.getStorageSync('customerInfo') || getApp().globalData.customerInfo;
        let nowTime = new Date().getTime();
        let endtime;
        let drawButtonColor = "#000";
        let drawButtonText = "";
        let drawTitleText = "";
        let drawTitleColor = "#000";
        let hasPromulgate = false;

        // 会员等级是否满足 -1不满足活动资格
        // let level = obj.activityInfo.memberLevelJson.indexOf(obj.memberLevelId);
        // 活动未开始   订阅提醒阶段
        if (nowTime < obj.exTime.exStartTime) {
          endtime = obj.exTime.exStartTime;
          this.data.activityStatus = 0;
          let _time = this.getFormatDate(obj.exTime.exStartTime);
          drawTitleText = `将于${_time}开放登记`;
          const _remindSuccess = await this.isSecondRemindRquest(itemName, obj.activityInfo, customerInfo);
          if (_remindSuccess) {
            this.data.remindMeStatus = "YES";
            drawButtonColor = "rgba(0,0,0,.54)";
            drawButtonText = '已设置开售提醒';
          } else {
            this.data.remindMeStatus = "NO";
            drawButtonText = '+ 开售提醒';
          }
          return this.setData({
            drawButtonColor,
            drawButtonText,
            drawTitleText,
            drawTitleColor
          });
        }
        this.data.remindMeStatus = ""
        const asObj = (obj.activityInfo && obj.activityInfo.activitySelectionRecord) ? obj.activityInfo
          .activitySelectionRecord : null;
        // 登记时间
        if (nowTime > obj.exTime.exStartTime && nowTime < obj.exTime.exEndTime) {
          if (asObj) {
            endtime = obj.exTime.expromulgateTime
          } else {
            endtime = obj.exTime.exEndTime
          }
          this.data.activityStatus = 1;
        }
        //登记时间结束--公布时间
        if (nowTime > obj.exTime.exEndTime && nowTime < obj.exTime.expromulgateTime) {
          endtime = obj.exTime.expromulgateTime;
          this.data.activityStatus = 2;
        }
        //公布时间---购买结束时间
        if (nowTime > obj.exTime.expromulgateTime && nowTime < obj.exTime.buyEndTime) {
          this.data.activityStatus = 3;
        }

        // 购买结束时间--活动结束
        if (nowTime > obj.exTime.buyEndTime && nowTime < obj.exTime.activityStopTime) {
          this.data.activityStatus = 4;
        }
        // 活动结束之后（当前时间大于活动结束时间）
        if (nowTime > obj.exTime.activityStopTime) {
          drawButtonText = '查看详情';
          drawTitleText = '活动已结束';
          return this.setData({
            drawButtonColor,
            drawButtonText,
            drawTitleText,
            drawTitleColor
          });
        }

        if (!!customerInfo) {
          //参与登记状态 包含 可登记和不可登记时间段
          if (this.data.activityStatus == 1) {
            drawTitleText = "开放登记";
            if (!asObj) {
              drawButtonText = '立即登记';
              drawButtonColor = "rgb(0,0,0)";
            } else {
              drawButtonText = '等待公布结果';
              drawButtonColor = "rgba(0,0,0,.54)";
            }
          } else if (this.data.activityStatus == 2) {
            //参与登记状态 包含 可登记和不可登记时间段
            drawTitleText = "登记结束";
            drawButtonColor = "rgba(0,0,0,.54)";
            if (!asObj) {
              drawButtonText = '登记已结束';
            } else {
              drawButtonText = '等待公布结果';
            }
          } else if (this.data.activityStatus == 3) {
            if (asObj) {
              //  订单筛选
              let _order = null;
              for (let i = 0; i < orderLists.length; i++) {
                const _els = orderLists[i];
                let ot = new Date(_els.createTime).getTime();
                if (_els.items[0].itemId == itemId && ot > obj.exTime.exCreateTime) {
                  _order = _els;
                }
              }

              const _activitySelectionRecordStatus = asObj.activitySelectionRecordStatus || null;
              //默认状态兼容其他状态签
              if (_activitySelectionRecordStatus == 1 || _activitySelectionRecordStatus == 2) {
                drawTitleText = '公布结果';
                drawButtonText = '未中签';
                drawButtonColor = "rgba(0,0,0,.54)";
              } else if (_activitySelectionRecordStatus == 3) {
                drawTitleColor = "#CB171A";
                drawTitleText = '恭喜中签';
                drawButtonText = '立即购买';
                nowTime = new Date().getTime();
              } else if (_order && _order.status) {
                nowTime = new Date().getTime();
                let endTime = new Date(_order.planEndTime).getTime();
                if (['WAIT_BUYER_PAY', 'BUYER_PART_PAYMENT'].includes(_order.status)) {
                  drawTitleColor = "#CB171A";
                  drawTitleText = '恭喜中签';
                  drawButtonText = '待支付';
                  this.start(endTime - nowTime);
                } else if (['WAIT_SELLER_SEND_GOODS'].includes(_order.status)) {
                  drawTitleColor = "#CB171A";
                  drawTitleText = '恭喜中签';
                  drawButtonText = '支付成功'
                } else {
                  drawTitleColor = "#CB171A";
                  drawTitleText = '恭喜中签';
                  drawButtonText = '查看订单'
                }
              } else if (_activitySelectionRecordStatus == 5) {
                drawTitleColor = "#CB171A";
                drawTitleText = '恭喜中签';
                drawButtonText = '查看订单';
              } else {
                drawTitleText = '公布结果';
                drawButtonColor = "rgba(0,0,0,.54)";
                drawButtonText = '未中签';
              }
            } else {
              drawButtonColor = "rgba(0,0,0,.54)";
              drawButtonText = '登记已结束';
              drawTitleText = '未登记';
            }
          } else if (this.data.activityStatus == 4) {
            //购买时间结束
            this.end()
            drawButtonText = '查看详情';
            drawTitleText = '活动结束';
          }
        }
        this.setData({
          drawButtonColor,
          drawButtonText,
          drawTitleText,
          drawTitleColor
        })
      } catch (e) {}
    },
    formatDate(date) {
      let data = date.slice(5, 10).replace('-', '月') + '日' + date.slice(11, 19)
      let month = data.substring(0, 2)
      if (month < 10) {
        data = data.slice(1)
      }
      return data
    },
    // 倒计时
    start(timestamp) {
      // 避免可能出现的倒计时重叠情况
      this.clearTimer();
      if (timestamp <= 0) return;
      let seconds = timestamp / 1000
      this.data.timer = setInterval(() => {
        seconds--;
        // 发出change事件
        if (seconds < 0) {
          return this.end();
        }
        this.formatTime(seconds);
      }, 1000);
    },
    // 格式化时间
    formatTime(seconds) {
      // 小于等于0的话，结束倒计时
      seconds <= 0 && this.end();
      let [day, hour, minute, second] = [0, 0, 0, 0];
      // 判断是否显示“天”参数，如果不显示，将天部分的值，加入到小时中
      // hour为给后面计算秒和分等用的(基于显示天的前提下计算)
      hour = Math.floor(seconds / (60 * 60));
      minute = Math.floor(seconds / 60) - hour * 60 - day * 24 * 60;
      second = Math.floor(seconds) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
      // 如果小于10，在前面补上一个"0"
      hour = hour < 10 ? '0' + hour : hour;
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;
      // this.h = hour;
      // this.i = minute;
      // this.s = second;
      this.setData({
        showDate: ` ${hour}:${minute}:${second}`
      })
    },
    // 停止倒计时
    end() {
      this.clearTimer();
      setTimeout(() => {
        this.setData({
          showDate: ""
        })
        // this.getDrawInfo()
      }, 1000);
    },
    // 清除定时器
    clearTimer() {
      if (this.data.timer) {
        // 清除定时器
        clearInterval(this.data.timer);
        this.data.timer = null;
      }
    },
    getFormatDate(timestamp) {
      const date = new Date(timestamp);
			const _month = date.getMonth() + 1;
      const month = _month > 9 ? _month : `0${_month}`;
      const day = date.getDate() > 9 ? date.getDate() : `0${date.getDate()}`;
      const hours = date.getHours() > 9 ? date.getHours() : `0${date.getHours()}`;
      const minutes = date.getMinutes() > 9 ? date.getMinutes() : `0${date.getMinutes()}`;

      return `${month}月${day}日`;
    },
    clickGoodsItem(e) {
      let {
        mf_data
      } = this.properties;
      let {
        item,
        items
      } = e.currentTarget.dataset;
      item = item || items
      if (!item?.goods?.itemId || !item?.goods?.valueId) return;
      if (!this.clickTimer) {
        this.clickTimer = setTimeout(() => {
          this.clickTimer = null;
          this.clickGoodsTrack(item, mf_data);
          let url = '/pages/item/balloutTime'
          wx.navigateTo({
            url: item.goods.itemId ? `${url}?id=${item.goods.itemId}&valueId=${item.goods.valueId}` : url
          })
        }, 200)
      }
    },
    //  商品点击埋点
    clickGoodsTrack(item, mf_data) {
      const {
        trackingParams,
        name1
      } = mf_data;
      try {
        const _trackingParams = trackingParams ? JSON.parse(trackingParams) : null;
        const module_name = (_trackingParams && _trackingParams.module_name) ? _trackingParams.module_name : "";
        const tab_name = (_trackingParams && _trackingParams.tab_name) ? _trackingParams.tab_name : "";
        this.triggerEvent('triggerComponent', {
          data: {
            item: item.goods,
            type: 'itemClick',
            module_name: module_name || name1,
            tab_name: tab_name
          }
        }, {
          bubbles: true,
          composed: true
        });
      } catch (e) {}
    },
    //  订阅消息按钮点击
    clickGoodsBtn(e) {
      const {
        currentTarget: {
          dataset: {
            items: {
              drawInfo,
              goods
            }
          }
        }
      } = e;
      if (this.data.remindMeStatus === 'NO' && drawInfo && goods) {
        this.remindRequest(drawInfo.activityInfo, goods.itemName)
      } else {
        this.clickGoodsItem(e)
      }
    },
    //开售提醒订阅
    remindRequest(activityInfo, itemName) {
      let that = this
      let templateId = ['3biNaYhS0dwQKynRfig5SI5ZEb_RVewTSAd0PE1CqgE',
        'u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc'
      ];
      wx.requestSubscribeMessage({
        tmplIds: templateId,
        success(res) {
          if (res['3biNaYhS0dwQKynRfig5SI5ZEb_RVewTSAd0PE1CqgE'] == "accept" && res
            .u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc == 'accept') {
            that.requestdrawMessage(activityInfo, itemName)
          } else if (res['3biNaYhS0dwQKynRfig5SI5ZEb_RVewTSAd0PE1CqgE'] == "accept") {
            that.startDrawMessage(1, activityInfo, itemName)
          } else if (res.u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc == 'accept') {
            that.resultDrawMessage(1, activityInfo, itemName)
          }
        },
        fail(res) {
          that.requestdrawMessage(activityInfo, itemName)
        },
        complete(res) {}
      });
    },
    async requestdrawMessage(activityInfo, itemName) {
      // trial 测试版  formal正式版
      let remind = await this.startDrawMessage(0, activityInfo, itemName);
      let result = await this.resultDrawMessage(0, activityInfo, itemName);
      if (remind && result) {
        // wx.showToast({
        //   title: '订阅成功',
        //   icon: "success",
        //   mask: true,
        //   duration: 1000
        // });
				this.triggerEvent('triggerComponent', {
				  data: {
				    msg: "订阅成功",
				    type: "showToast"
				  }
				}, {
				  bubbles: true,
				  composed: true
				});
        setTimeout(() => {
          this.balloutInit()
        }, 0)
      }
    },
    async startDrawMessage(flag, activityInfo, itemName) {
      let userSpecialInfo = wx.getStorageSync("userSpecialInfo");
      const accountInfo = wx.getAccountInfoSync()
      let customerInfo = wx.getStorageSync("customerInfo") || getApp().globalData.customerInfo;
      let page = `/pages/item/item?id=${this.goodsId}&valueId=${this.valueId}&valueName=${this.colorName}`
      if (customerInfo) {
        const api = getApp().globalData.api;
        let res = await api.sendSubMessage({
          method: 'POST',
          header: {
            jwt: customerInfo.jwt
          },
          query: {
            name: '甄选佳酿活动开始提醒',
            appId: accountInfo.miniProgram.appId,
            openId: userSpecialInfo.openid,
            params: {
              itemName: itemName,
              startTime: activityInfo.activitySelectionStartTime,
              miniprogramState: api.environment,
              page: page,
              activityId: activityInfo.activitySelectionId,
              activityName: activityInfo.activitySelectionName
            },
          },
        });
        if (res.code == 1000) {
          if (flag) {
            // wx.showToast({
            //   title: '订阅成功',
            //   icon: "success",
            //   mask: true,
            //   duration: 1000
            // });
						this.triggerEvent('triggerComponent', {
						  data: {
						    msg: "订阅成功",
						    type: "showToast"
						  }
						}, {
						  bubbles: true,
						  composed: true
						});
            this.balloutInit()
          }
          return true
        } else {
          // wx.showToast({
          //   title: res.msg,
          //   icon: 'none',
          //   mask: true,
          //   duration: 1000
          // });
					this.triggerEvent('triggerComponent', {
					  data: {
					    msg: res.msg,
					    type: "showToast"
					  }
					}, {
					  bubbles: true,
					  composed: true
					});
          return false
        }
      }
    },
    async resultDrawMessage(flag, activityInfo, itemName) {
      let userSpecialInfo = wx.getStorageSync("userSpecialInfo");
      const accountInfo = wx.getAccountInfoSync()
      let customerInfo = wx.getStorageSync("customerInfo") || getApp().globalData.customerInfo;
      let page = `/pages/item/item?id=${this.goodsId}&valueId=${this.valueId}&valueName=${this.colorName}`
      if (customerInfo) {
        const api = getApp().globalData.api;
        let res = await api.sendSubMessage({
          method: 'POST',
          header: {
            jwt: customerInfo.jwt
          },
          query: {
            name: '甄选佳酿活动结果通知',
            appId: accountInfo.miniProgram.appId,
            openId: userSpecialInfo.openid,
            params: {
              itemName: itemName,
              publicationTime: activityInfo.promulgateTime,
              page: page,
              miniprogramState: api.environment,
              activityId: activityInfo.activitySelectionId,
              activityName: activityInfo.activitySelectionName
            },
          },
        });
        if (res.code == 1000) {
          if (flag) {
            // wx.showToast({
            //   title: '订阅成功',
            //   icon: "success",
            //   mask: true,
            //   duration: 1000
            // });
						this.triggerEvent('triggerComponent', {
						  data: {
						    msg: "订阅成功",
						    type: "showToast"
						  }
						}, {
						  bubbles: true,
						  composed: true
						});
            this.balloutInit()
          }
          return true
        } else {
          // wx.showToast({
          //   title: res.msg,
          //   icon: 'none',
          //   mask: true,
          //   duration: 1000
          // });
					this.triggerEvent('triggerComponent', {
					  data: {
					    msg: res.msg,
					    type: "showToast"
					  }
					}, {
					  bubbles: true,
					  composed: true
					});
          return false
        }
      }
    },
  }
});